package com.tanguy.user.ui.window

import android.content.Context
import android.support.design.widget.TabLayout
import android.text.InputFilter
import android.text.InputType
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.jakewharton.rxbinding2.widget.RxTextView
import com.tanguy.user.R
import com.tanguy.user.base.BasePopupWindow
import com.tanguy.user.bean.User
import com.tanguy.user.net.http.HttpManager
import com.tanguy.user.ui.me.activity.account.PhoneActivity
import com.tanguy.user.utlis.extend.*
import io.reactivex.disposables.Disposable
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity


/**
 * Created by dab on 2017/9/29 0029 10:39
 * loginType 0:验证码登录 1:密码登录 -1:取消登录
 */

class LoginWindow(context: Context?, private val result: (user: User?, loginType: Int) -> Unit) : BasePopupWindow(context) {

    override fun setContentRes(): Int = R.layout.window_login
    var loginType = 0
    lateinit var setPwd: TextView
    lateinit var psd: EditText
    lateinit var phone: EditText
    var countDownTimer: Disposable? = null
    lateinit var mTvCaptcha: TextView
    private var loginSucceed = false
    private var phoneIsNull = true
    private var psdIsNull = true
    override fun initView(view: View) {
        super.initView(view)
        view.apply {
            click(R.id.iv_close) {
                dismiss()
            }
            click(R.id.btn_login) { login() }
            click(R.id.tv_get_captcha) { getCaptcha() }
            click(R.id.tv_set_pwd) {
                context.startActivity<PhoneActivity>()
                dismiss()
            }
            mTvCaptcha = find(R.id.tv_get_captcha)
            setPwd = find(R.id.tv_set_pwd)
            psd = find(R.id.et_psd)
            phone = find(R.id.et_phone)
            val tab = find<TabLayout>(R.id.tab_title_type)
            psd.transformationMethod = HideReturnsTransformationMethod.getInstance()
            tab.addTab(tab.newTab().setText("验证码登录"))
            tab.addTab(tab.newTab().setText("密码登录"))
            tab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabReselected(tab: TabLayout.Tab?) {}

                override fun onTabUnselected(tab: TabLayout.Tab?) {}

                override fun onTabSelected(tab: TabLayout.Tab?) {
                    if (tab == null) return
                    loginType = tab.position
                    refreshUI(loginType)//切换登录的方式
                }
            })
        }
        RxTextView.textChanges(phone)
                .subscribe {
                    phoneIsNull = TextUtils.isEmpty(it)
                    if (!phoneIsNull && !psdIsNull) {
                        view.find<View>(R.id.btn_login).setBackgroundResource(R.drawable.shape_gradient)
                    } else {
                        view.find<View>(R.id.btn_login).setBackgroundResource(R.color.color_cecece)
                    }
                }
        RxTextView.textChanges(psd)
                .subscribe {
                    psdIsNull = TextUtils.isEmpty(it)
                    if (!phoneIsNull && !psdIsNull) {
                        view.find<View>(R.id.btn_login).setBackgroundResource(R.drawable.shape_gradient)
                    } else {
                        view.find<View>(R.id.btn_login).setBackgroundResource(R.color.color_cecece)
                    }
                }


    }


    private fun refreshUI(loginType: Int) {
        if (loginType == 0) {
            //验证码登录
            mTvCaptcha.visibility = View.VISIBLE
            setPwd.visibility = View.INVISIBLE
            psd.hint = "请输入验证码"
            psd.setText("")
            val drawable = psd.context.resources.getDrawable(R.mipmap.yanzhengma)
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight);
            psd.setCompoundDrawables(drawable, null, null, null)

            //可见
            psd.transformationMethod = HideReturnsTransformationMethod.getInstance()
            val inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_NORMAL
            psd.inputType = inputType

            psd.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(6))
        } else {
            //密码登录
            mTvCaptcha.visibility = View.GONE
            setPwd.visibility = View.VISIBLE
            psd.hint = "请输入密码"
            psd.setText("")
            //不可见
            psd.transformationMethod = PasswordTransformationMethod.getInstance()
//            val inputType =InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL
//            psd.inputType= inputType
            val drawable = psd.context.resources.getDrawable(R.mipmap.mima)
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight);
            psd.setCompoundDrawables(drawable, null, null, null)
            psd.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(20))
        }
    }

    private fun getCaptcha() {
        val phone = getEditTextString(phone)
        if (!checkPhoneNumber(phone)) return

        HttpManager.sendSmsCode(phone, 1)
                .requestSucceed(this) {
                    // 获取验证码
                    countDownTimer = captchaCountDownTimer { finish, msg ->
                        mTvCaptcha.isClickable = finish
                        mTvCaptcha.text = msg
                    }
                }


    }

    private fun login() {
        val password = getEditTextString(psd)
        val phone = getEditTextString(phone)
        if (!checkPhoneNumber(phone)) return
        if (loginType == 0) {
            if (!checkCaptcha(password)) return
            HttpManager.loginBySms(phone, password)
                    .requestSucceed(this) { user ->
                        checkLogin(user) {
                            if (it != null) {
                                showToast(it)
                                return@checkLogin

                            }
                            loginSucceed = true
                            result.invoke(user, loginType)
                            dismiss()
                        }

                    }

        } else {
            if (!checkPassword(password)) return
            HttpManager.paswLogin(phone, password)
                    .requestSucceed(this@LoginWindow) { data ->
                        checkLogin(data) {
                            if (it != null) {
                                showToast(it)
                                return@checkLogin
                            }
                            loginSucceed = true
                            result.invoke(data, loginType)
                            dismiss()
                        }
                    }
        }

    }


    override fun dismiss() {
        super.dismiss()
        if (!loginSucceed) {
            result.invoke(null, -1)
        }
        countDownTimer?.apply {
            if (isDisposed) dispose()
        }

    }
}
